// 源插件
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
// import { NumberDivide, DateDiff, FormatnumberZero, Mover, DateStamp } from '@/function.js'

// 视图插件
import {
  Button,
  BackTop,
  Empty,
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Upload,
} from 'antd';
import echarts from 'echarts-forstock/lib/echarts';
import 'echarts-forstock/lib/chart/line';
import 'echarts-forstock/lib/chart/bar';
import 'echarts-forstock/lib/chart/candlestickUSA';
import 'echarts-forstock/lib/chart/candlestick';
import 'echarts-forstock/lib/chart/effectScatter';
import 'echarts-forstock/lib/component/grid';
import 'echarts-forstock/lib/component/tooltip';
import 'echarts-forstock/lib/component/markLine';
import 'echarts-forstock/lib/component/markPoint';
import 'echarts-forstock/lib/component/title';
import 'echarts-forstock/lib/component/dataZoom';
import 'echarts-forstock/lib/component/markArea';
import 'echarts-forstock/lib/component/legend';

import zrender from 'zrender';

// 外部组件
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Loading from '@/components/Loading/Loading';
import zTools from './zTools';
// import { getData } from './mockData.js'

// css OR less预编译器
// import styles from './All.less';

// 图片

// 算数
import { DateDiff, FormatnumberZero, Mover, NumberDivide } from '@/function.js';

function calculateMA(dayCount, data) {
  const result = [];
  for (let i = 0, len = data.length; i < len; i++) {
    if (i < dayCount) {
      result.push('-');
      continue;
    }
    let sum = 0;
    for (let j = 0; j < dayCount; j++) {
      sum += data[i - j][1];
    }
    result.push(sum / dayCount);
  }
  return result;
}

/* 对准鼠标在画布定位点 */
function windowTocanvas(canvas, x, y) {
  const bbox = canvas.getBoundingClientRect();
  return {
    x: x - bbox.left,
    y: y - bbox.top,
    boxGap: bbox.left,
    // x: x,
    // y: y,
  };
}

let myChart;
let option = null; // 总图;
let zr;

class Stock extends PureComponent {
  componentWillMount() {}

  state = {
    klineStyle: false, // 美国线标志位
    line: false,
    zIndex: -1,
  };

  /**
   *  Describe:
   *  Created by xjc on 2019/7/17
   */

  setOption(dates, data, dataGray, volumes) {
    const { klineStyle } = this.state;

    if (option === null) {
      option = {
        // backgroundColor: '#21202D',

        // Animation
        animation: false,

        // Legend
        legend: {
          top: 30,
          data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30', '成交量'],
          inactiveColor: '#777',
          textStyle: {
            color: '#444',
          },
        },

        // Grid
        grid: [
          {
            left: '10%',
            right: '8%',
            height: '44%',
          },
          {
            left: '10%',
            right: '8%',
            top: '57%',
            height: '15%',
          },
          {
            left: '10%',
            right: '8%',
            top: '74%',
            height: '15%',
            bottom: 50,
          },
        ],

        // Tooltip
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            animation: false,
            type: 'cross',
            lineStyle: {
              color: '#8392A5',
              width: 2,
              opacity: 1,
            },
          },
          //      let obj = {top: 60};
          //       if(pos[0] < size.viewSize[0]/2){
          //         obj.left = pos[0]+size.viewSize[0]/20;
          //       }else{
          //         obj.left = pos[0]-size.viewSize[0]/20-200;
          //       }
          //      /* obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = pos[0];*/
          //     return obj;
          // /*return [point[0]+50, point[1]];*/
          position(pos, params, dom, rect, size) {
            // 固定在顶部
            const obj = { top: 60 };
            obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5;
            return obj;
          },
          padding: 10,
        },

        // Zoom
        dataZoom: [
          {
            textStyle: {
              color: '#8392A5',
            },
            handleIcon:
              'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
            handleSize: '80%',
            dataBackground: {
              areaStyle: {
                color: '#8392A5',
              },
              lineStyle: {
                opacity: 0.8,
                color: '#8392A5',
              },
            },
            handleStyle: {
              color: '#fff',
              shadowBlur: 3,
              shadowColor: 'rgba(0, 0, 0, 0.6)',
              shadowOffsetX: 2,
              shadowOffsetY: 2,
            },
            xAxisIndex: [0, 1],
            startValue: dates.length - 50,
            endValue: dates.length - 1,
            minValueSpan: 10,
          },
          {
            show: true,
            xAxisIndex: [0, 1],
            type: 'inside',
            minValueSpan: 10,
          },
          {
            show: true,
            xAxisIndex: [0, 1],
            type: 'inside',
            top: '85%',
            minValueSpan: 10,
          },
        ],

        // X
        xAxis: [
          {
            type: 'category',
            data: dates,
            // boundaryGap: false,
            scale: true,
            axisTick: { show: false },
            axisLine: { onZero: false, lineStyle: { color: '#8392A5' } },
            splitLine: { show: false },
            splitNumber: 20,
            min: 'dataMin',
            max: 'dataMax',
            // axisPointer: {
            //   z: 100
            // }
          },
          {
            type: 'category',
            gridIndex: 1,
            data: dates,
            // boundaryGap: false,
            scale: true,
            axisLine: { onZero: false, lineStyle: { color: '#8392A5' } },
            axisTick: { show: false },
            splitLine: { show: false },
            axisLabel: { show: false },
            splitNumber: 20,
            min: 'dataMin',
            max: 'dataMax',
            tooltip: {
              show: false,
            },
            // axisPointer: {
            //     label: {
            //         formatter: function (params) {
            //             let seriesValue = (params.seriesData[0] || {}).value;
            //             return params.value
            //             + (seriesValue != null
            //                 ? '\n' + echarts.format.addCommas(seriesValue)
            //                 : ''
            //             );
            //         }
            //     }
            // }
          },
          {
            type: 'category',
            gridIndex: 2,
            data: dates,
            // boundaryGap: false,
            scale: true,
            axisLine: { onZero: false, lineStyle: { color: '#8392A5' } },
            axisTick: { show: false },
            splitLine: { show: false },
            axisLabel: { show: false },
            splitNumber: 20,
            min: 'dataMin',
            max: 'dataMax',
            tooltip: {
              show: false,
            },
          },
        ],

        // Y
        yAxis: [
          {
            type: 'value',
            scale: true,
            axisLine: { lineStyle: { color: '#8392A5' } },
            splitLine: { show: false },
            max(value) {
              return FormatnumberZero(value.max * 1.01, 0);
            },
            min(value) {
              return FormatnumberZero(value.min * 0.99, 0);
            },
          },
          {
            scale: true,
            gridIndex: 1,
            splitNumber: 2,
            axisLine: { lineStyle: { color: '#8392A5' } },
            axisLabel: {
              show: true,
              formatter(value, index) {
                let newValue;
                const valueString = value.toString();
                if (valueString.length >= 9) {
                  newValue = value / 100000000;
                } else if (valueString.length < 9 && valueString.length >= 5) {
                  newValue = value / 10000;
                } else {
                  newValue = value;
                }
                return `${newValue}W`;
              },
            },
            /* axisLine: {show: false},
            axisTick: {show: false}, */
            splitLine: { show: false },
          },
          {
            scale: true,
            gridIndex: 2,
            splitNumber: 2,
            axisLine: { lineStyle: { color: '#8392A5' } },
            /* axisLabel: {show: true, formatter:  function (value, index) {
                 let newValue;
                 let valueString = value.toString();
                 if(valueString.length>=9){
                   newValue = value/100000000;
                 }else if(valueString.length<9&&valueString.length>=5){
                   newValue = value/10000;
                 }else{
                   newValue = value;
                 }
                 return newValue+'W';
               }}, */
            /* axisLine: {show: false},
            axisTick: {show: false}, */
            splitLine: { show: false },
          },
        ],

        // Pointer
        axisPointer: {
          link: { xAxisIndex: 'all' },
          label: {
            backgroundColor: '#777',
          },
        },

        // v
        visualMap: {
          show: false,
          seriesIndex: 5,
          dimension: 2,
          pieces: [
            {
              value: 1,
              color: '#00da68',
            },
            {
              value: -1,
              color: '#FD1050',
            },
          ],
        },

        // S
        series: [
          {
            type: klineStyle ? 'candlestickUSA' : 'candlestick',
            name: '日K',
            data,
            markLine: {
              symbol: ['none', 'none'],
              data: [
                {
                  name: 'Y 轴值为 100 的水平线',
                  yAxis: 7000,
                },
              ],
              smooth: true,
              showSymbol: false,
              lineStyle: {
                normal: {
                  color: 'rgba(200,200,200,0.9)',
                  type: 'dashed',
                },
              },
            },
            itemStyle: {
              normal: {
                color: '#FD1050',
                color0: '#00da68',
                borderColor: '#FD1050',
                borderColor0: '#00da68',
              },
            },
          },
          {
            name: 'MA5',
            type: 'line',
            data: calculateMA(5, data),
            symbol: 'none',
            smooth: true,
            showSymbol: false,
            lineStyle: {
              normal: {
                width: 1,
              },
            },
          },
          {
            name: 'MA10',
            type: 'line',
            symbol: 'none',
            data: calculateMA(10, data),
            smooth: true,
            showSymbol: false,
            lineStyle: {
              normal: {
                width: 1,
              },
            },
          },
          {
            name: 'MA20',
            type: 'line',
            symbol: 'none',
            data: calculateMA(20, data),
            smooth: true,
            showSymbol: false,
            lineStyle: {
              normal: {
                width: 1,
              },
            },
          },
          {
            name: 'MA30',
            type: 'line',
            symbol: 'none',
            data: calculateMA(30, data),
            smooth: true,
            showSymbol: false,
            lineStyle: {
              normal: {
                width: 1,
              },
            },
          },
          {
            name: 'Volume',
            type: 'bar',
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: volumes,
            itemStyle: {
              normal: {
                color(params) {
                  let color;
                  if (data[params.dataIndex][1] > data[params.dataIndex][0]) {
                    color = '#FD1050';
                  } else {
                    color = '#00da68';
                  }
                  return color;
                },
              },
            },
          },
          {
            name: 'MACD',
            type: 'bar',
            xAxisIndex: 2,
            yAxisIndex: 2,
            data: data.macds,
            itemStyle: {
              normal: {
                color(params) {
                  let color;
                  if (params.data >= 0) {
                    color = '#ef232a';
                  } else {
                    color = '#14b143';
                  }
                  return color;
                },
              },
            },
          },
          {
            name: 'DIF',
            type: 'line',
            smooth: true,
            showSymbol: false,
            xAxisIndex: 2,
            yAxisIndex: 2,
            data: data.difs,
          },
          {
            name: 'DEA',
            type: 'line',
            smooth: true,
            showSymbol: false,
            xAxisIndex: 2,
            yAxisIndex: 2,
            data: data.deas,
          },
        ],
        // graphic: [{
        //   type: 'line',
        //   z: 100,
        //   shape: {
        //     x1:100,
        //     y1:100,
        //     x2:200,
        //     y2:200,
        //   },
        //   style: {
        //     fill: '#fff',
        //     stroke: '#999',
        //     lineWidth: 2,
        //     shadowBlur: 8,
        //     shadowOffsetX: 3,
        //     shadowOffsetY: 3,
        //     shadowColor: 'rgba(0,0,0,0.3)'
        //   }
        // },]
      };
    }

    myChart.setOption(option, true);
  }

  resetOption(a) {
    switch (a) {
      case 'type0':
        option.series[0].type = this.state.klineStyle ? 'candlestickUSA' : 'candlestick';
      case 'line':
    }
    option.dataZoom[0].startValue = myChart.getOption().dataZoom[0].startValue;
    option.dataZoom[0].endValue = myChart.getOption().dataZoom[0].endValue;
    myChart.setOption(option, true);
  }

  render() {
    const { loading } = this.props;
    const { klineStyle, zIndex } = this.state;

    return (
      <PageHeaderWrapper title="股票图">
        <Card>
          <Button
            onClick={() => {
              this.setState({ klineStyle: !klineStyle });
              this.resetOption('type0');
            }}
          >
            {klineStyle ? '蜡烛线' : '美国线'}
          </Button>

          <Button
            onClick={() => {
              this.setState({ zIndex: 12 });
              this.resetOption('line');
            }}
          >
            划线
          </Button>

          <div>
            <div id="main" style={{ width: '100%', height: '666px', position: 'absolute' }} />
            <div
              id="drawbox"
              style={{
                width: '100%',
                height: '293px',
                paddingLeft: '10%',
                paddingRight: '8%',
                paddingTop: 60,
                position: 'absolute',
                zIndex,
              }}
            >
              <canvas id="draw" width="100%" height="293px" style={{ border: '2px solid #69c ' }} />
            </div>
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const main = document.getElementById('main');
    const draw = document.getElementById('draw');
    myChart = echarts.init(main, '', { renderer: 'svg' });
    // drawbox.offsetTop = 353;
    // getData();

    this.setOption(window.dates, window.data, window.dataGray, window.volumes);

    const drawbox = document.getElementById('drawbox');
    draw.width = drawbox.getBoundingClientRect().width * 0.82;
    zr = zrender.init(draw);
    // Line
    const canvas = document.getElementById('draw');

    let isDrag = false;
    const point_start = {};
    let point_end = {};
    let id = 0;
    let gap;
    canvas.onmousedown = function() {
      const loc = windowTocanvas(main, event.x, event.y);
      const { x } = loc;
      const { y } = loc;
      isDrag = true;
      // gap = (myChart.convertToPixel({xAxisIndex: 0}, 1)-myChart.convertToPixel({xAxisIndex: 0}, 0))/2;
      point_start.x = parseInt(myChart.convertFromPixel({ xAxisIndex: 0 }, x));
      point_start.y = parseInt(myChart.convertFromPixel({ yAxisIndex: 0 }, y));

      option.series.push({
        id: id++,
        type: 'line',
        z: 100,
        data: [[point_start.x, point_start.y], [point_start.x, point_start.y]],
        itemStyle: {
          normal: { color: '#333' },
        },
        style: {
          fill: '#fff',
          stroke: '#999',
          lineWidth: 2,
          shadowBlur: 8,
          shadowOffsetX: 3,
          shadowOffsetY: 3,
          shadowColor: 'rgba(0,0,0,0.3)',
        },
      });
      option.dataZoom[0].startValue = myChart.getOption().dataZoom[0].startValue;
      option.dataZoom[0].endValue = myChart.getOption().dataZoom[0].endValue;
      myChart.setOption(option, true);
      // myChart.setOption({
      //   series: [
      //     {
      //     type: 'line',
      //     z: 100,
      //     shape: {
      //       x1:point_start.x,
      //       y1:point_start.y,
      //       x2:point_start.x,
      //       y2:point_start.y,
      //     },
      //     style: {
      //       fill: '#fff',
      //       stroke: '#999',
      //       lineWidth: 2,
      //       shadowBlur: 8,
      //       shadowOffsetX: 3,
      //       shadowOffsetY: 3,
      //       shadowColor: 'rgba(0,0,0,0.3)'
      //     }
      //   },]
      // });
    };

    canvas.onmousemove = function() {
      if (isDrag) {
        const loc = windowTocanvas(main, event.x, event.y);
        const { x } = loc;
        const { y } = loc;

        point_end = myChart.convertFromPixel({ seriesIndex: 0 }, [x, y]);
        point_end.x = parseInt(point_end[0]);
        point_end.y = parseInt(point_end[1]);
        option.series[option.series.length - 1].data = [
          [point_start.x, point_start.y],
          [point_end.x, point_end.y],
        ];
        myChart.setOption(option);
      }
    };

    canvas.onmouseup = function() {
      const loc = windowTocanvas(canvas, event.x, event.y);
      const { x } = loc;
      const { y } = loc;

      isDrag = false;
    };
  }

  componentWillUnmount() {}
}

export default Stock;
